import { User } from '../models/User.js';
import { Student } from '../models/Student.js';
import { Teacher } from '../models/Teacher.js';
import { MarketingDepartment } from '../models/MarketingDepartment.js';
import { Class } from '../models/Class.js';
import { College } from '../models/College.js';
import { Dormitory } from '../models/Dormitory.js';
import { DormBuilding } from '../models/DormBuilding.js';

const userModel = new User();
const studentModel = new Student();
const teacherModel = new Teacher();
const marketingModel = new MarketingDepartment();
const classModel = new Class();
const collegeModel = new College();
const dormitoryModel = new Dormitory();
const dormBuildingModel = new DormBuilding();

export class DashboardController {
  // 获取数据概览
  async getDashboardStats(req, res) {
    try {
      console.log('获取数据概览');

      const users = userModel.findAll();
      const students = studentModel.findAll();
      const teachers = teacherModel.findAll();
      const marketingDepartments = marketingModel.findAll();
      const classes = classModel.findAll();
      const colleges = collegeModel.findAll();
      const dormitories = dormitoryModel.findAll();
      const dormBuildings = dormBuildingModel.findAll();

      // 计算统计数据
      const totalUsers = users.length;
      const totalStudents = students.length;
      const totalTeachers = teachers.length;
      const totalMarketingDepartments = marketingDepartments.length;
      const totalClasses = classes.length;
      const totalColleges = colleges.length;
      const totalDormitories = dormitories.length;
      const totalDormBuildings = dormBuildings.length;

      // 计算宿舍入住率
      const totalBeds = dormitories.reduce((sum, dorm) => sum + dorm.totalBeds, 0);
      const occupiedBeds = dormitories.reduce((sum, dorm) => sum + dorm.occupiedBeds, 0);
      const occupancyRate = totalBeds > 0 ? (occupiedBeds / totalBeds * 100).toFixed(2) : 0;

      // 学院学生分布
      const collegeDistribution = colleges.map(college => {
        const collegeStudents = students.filter(student => student.college === college.name);
        return {
          name: college.name,
          count: collegeStudents.length
        };
      });

      // 市场部学生分布
      const marketingDistribution = marketingDepartments.map(dept => {
        const deptStudents = students.filter(student => student.marketingDepartment === dept.name);
        return {
          name: dept.name,
          count: deptStudents.length
        };
      });

      // 性别分布统计
      const genderDistribution = students.reduce((acc, student) => {
        const gender = student.gender || '未知';
        if (!acc[gender]) {
          acc[gender] = 0;
        }
        acc[gender]++;
        return acc;
      }, {});

      // 按月入学统计（基于enrollmentDate）
      const enrollmentByMonth = Array(12).fill(0);
      students.forEach(student => {
        if (student.enrollmentDate) {
          const month = new Date(student.enrollmentDate).getMonth();
          enrollmentByMonth[month]++;
        }
      });

      // 活跃学生数
      const activeStudents = students.filter(s => s.status === 'active').length;

      // 老师职称分布
      const teacherTitleDistribution = teachers.reduce((acc, teacher) => {
        const title = teacher.title || '未设置';
        if (!acc[title]) {
          acc[title] = 0;
        }
        acc[title]++;
        return acc;
      }, {});

      // 最近注册的学生
      const recentStudents = students
        .sort((a, b) => new Date(b.enrollmentDate) - new Date(a.enrollmentDate))
        .slice(0, 5);

      // 最近入职的老师
      const recentTeachers = teachers
        .sort((a, b) => new Date(b.hireDate) - new Date(a.hireDate))
        .slice(0, 5);

      res.json({
        totalUsers,
        totalStudents,
        activeStudents,
        totalTeachers,
        totalMarketingDepartments,
        totalClasses,
        totalColleges,
        totalDormitories,
        totalDormBuildings,
        occupancyRate: parseFloat(occupancyRate),
        totalBeds,
        occupiedBeds,
        collegeDistribution,
        marketingDistribution,
        genderDistribution,
        enrollmentByMonth,
        teacherTitleDistribution,
        recentStudents,
        recentTeachers
      });
    } catch (error) {
      console.error('获取数据概览失败:', error);
      res.status(500).json({ error: '获取失败' });
    }
  }
}